<?php
/**
 * @ClassName: Shopgoodsapply
 * @Description: 产品申请
 * @author: gydtrade
 * @Date: 2024-09-10 21:53
 * @Version: V1.0.0
 */

namespace app\admin\controller;

use app\common\enum\CommonEnum;
use app\common\enum\MerchantEnum;
use app\common\model;
use think\Controller;
use tpext\builder\traits\HasBuilder;

class Shopgoodsapply extends Controller
{
    use HasBuilder;

    protected $dataModel;

    protected $shop_type;
    protected $status;

    protected function initialize()
    {
        parent::initialize();

        $this->dataModel = new model\ShopGoods();
        $this->pageTitle = '产品申请';
        $this->enableField = 'status';
        $this->pagesize = 10;

        $this->indexWith = ['category', 'brand', 'cate', 'store', 'unit']; //列表页模型关联

        $this->status = input('status', 0);
        $this->shop_type = input('shop_type', 0);
    }

    /**
     * 构建搜索
     *
     * @return void
     */
    protected function buildSearch()
    {
        $search = $this->search;
        $search->select('shop_type', '产品归属')->options(MerchantEnum::storeTypeText(true))->default($this->shop_type);
        $search->select('store_id', '商家')->dataUrl(url('/admin/store.store/selectPage'));
        $search->select('status', '状态')->options([0 => '待审核', 2 => '已驳回'])->default($this->status);
    }

    /**
     * 构建搜索条件
     * @return array
     */
    protected function filterWhere()
    {
        $searchData = request()->get();

        $where = [];
        if (isset($searchData['shop_type']) && $searchData['shop_type'] != '') {
            $where[] = ['shop_type', 'eq', $searchData['shop_type']];
        }
        if (isset($searchData['store_id']) && $searchData['store_id'] != '') {
            $where[] = ['store_id', 'eq', $searchData['store_id']];
        }
        if (isset($searchData['status']) && $searchData['status'] != '') {
            $where[] = ['status', 'eq', $searchData['status']];
        } else {
            $where[] = ['status', 'in', [0, 2]];
        }
        return $where;
    }

    /**
     * 构建表格
     *
     * @return void
     */
    protected function buildTable(&$data = [])
    {
        $table = $this->table;

        $table->show('id', 'ID');
        $table->image('logo', '封面图')->thumbSize(60, 60);
        $table->match('shop_type', '产品归属')->options(MerchantEnum::storeTypeText(true))->mapClassGroup([[1, 'info'], [2, 'success']]);
        $table->show('name', '名称');
        $table->show('brand.name', '品牌');
        $table->show('category.name', '分类');
        $table->match('store_id', '商家')->to('{store_id}#{store.store_name}');
        $table->show('cost_price', '成本价');
        $table->show('sale_price', '销售价');
        $table->show('market_price', '市场价');
        $table->match('delivery_type', '配送方式')->options(model\ShopGoods::$service_types)->mapClassGroup([[1, 'info'], [2, 'success'], [3, 'danger']]);
        $table->show('delivery_price', '配送费');
        $table->match('unit_id', '单位')->to('{unit_id}#{unit.name}');
        $table->show('stock', '库存');
        $table->match('status', '状态')->options([0 => '待审核', 1 => '已通过', 2 => '已驳回'])->mapClassGroup([[0, 'info'], [1, 'success'], [2, 'danger']]);
        $table->show('review_opinion', '审核意见');
        $table->show('review_time', '审核时间');

        $table->fields('times', '申请/修改时间')->with(
            $table->show('create_time', '申请时间'),
            $table->show('update_time', '修改时间')
        )->getWrapper()->addStyle('width:160px');

        $table->sortable('id, review_time, create_time');

        foreach ($data as &$d) {
            $d['__h_p__'] = $d['status'] != 0;
            $d['__h_unp__'] = $d['status'] != 0;
        }
        unset($d);

        $table->getToolbar()
//            ->btnAdd()
            ->btnEnableAndDisable('通过', '拒绝')
            ->btnRefresh();

        $table->getActionbar()
            ->btnEdit()
            ->btnDelete()
            ->btnPostRowid('pass', url('/admin/shopgoodsapply/enable', ['state' => 1]), '通过', 'btn-success', '', '')
            ->btnPostRowid('unpass', url('/admin/shopgoodsapply/enable', ['state' => 0]), '拒绝', 'btn-danger', '', '')
            ->mapClass([
                'pass' => ['hidden' => '__h_p__'],
                'unpass' => ['hidden' => '__h_unp__'],
            ]);
    }

    /**
     * 审核
     * @param $state
     * @return \think\response\Json
     */
    public function enable($state)
    {
        $ids = input('post.ids', '');
        $ids = array_filter(explode(',', $ids), 'strlen');

        if (empty($ids)) {
            return json(['code' => 0, 'msg' => '参数有误']);
        }

        if ($state) {
            $remark = '审核通过';
            $status = 1;
        } else {
            $remark = '审核不通过';
            $status = 2;
        }
        $res = 0;
        foreach ($ids as $id) {
            if ($this->trans($id, $remark, $status)) {
                $res += 1;
            }
        }
        if ($res) {
            return json(['code' => 1, 'msg' => '成功操作' . $res . '条数据']);
        } else {
            trace('审核操作失败');
            return json(['code' => 0, 'msg' => '审核操作失败']);
        }
    }

    /**
     * 审核操作
     * @param $id
     * @param $remark
     * @param $state
     * @return model\OperationCenter|\think\response\Json
     */
    private function trans($id, $remark, $state = 1)
    {
        $records = $this->dataModel::where('id', $id)->find();

        if (!$records) {
            return json(['code' => 0, 'msg' => '记录不存在']);
        }
        if ($records['status'] != 0) {
            return json(['code' => 0, 'msg' => '记录状态不是待审核状态']);
        }

        $up_data = [
            'status' => $state,
            'review_opinion' => $remark,
            'update_time' => date_now(),
        ];
        if ($state == 1) {
            $up_data['review_time'] = date_now();
        }
        $res = $this->dataModel::where('id', $id)->update($up_data);

        return $res;
    }

    /**
     * 构建表单
     *
     * @param boolean $isEdit
     * @param array $data
     */
    protected function buildForm($isEdit, &$data = [])
    {
        $form = $this->form;

        $form->text('name', '名称')->readonly();
        $form->show('brand.name', '品牌');
        $form->show('category.name', '分类');
        $form->match('store_id', '商家')->to('{store_id}#{store.store_name}');
        $form->show('cost_price', '成本价');
        $form->show('sale_price', '销售价');
        $form->show('market_price', '市场价');
        $form->radio('delivery_type', '服务类型')->options(model\ShopGoods::$service_types)->readonly()->when(1)->with(
            $form->show('delivery_price', '配送费')
        );
        $form->match('unit_id', '单位')->to('{unit_id}#{unit.name}');
        $form->show('stock', '库存');
        if ($data['shop_type'] == MerchantEnum::water) {
            if ($data['delivery_type'] == 1 || $data['delivery_type'] == 3) {
                $form->show('delivery_time', '送达时效/小时');
            }
            $form->show('shelf_life_unopened', '未开封保质期/月');
            $form->show('shelf_life_opened', '开封保质期/天');
        }
        $form->textarea('description', '产品描述')->readonly();
        $form->image('logo', '封面图')->thumbSize(100, 100)->readonly();
        $form->images('images', '详情图')->thumbSize(100, 100)->readonly();
        $form->images('creden_imgs', '资质文件')->thumbSize(100, 100)->readonly();
        $form->radio('status', '状态')->options([0 => '待审核', 1 => '已通过', 2 => '已驳回'])->when(2)->with(
            $form->textarea('review_opinion', '审核意见')->required()
        );

        if ($data['status']) {
            $form->show('review_opinion', '审核意见');
            $form->show('review_time', '审核时间');
        }

        if ($isEdit) {
            $form->show('create_time', '添加时间');
            $form->show('update_time', '修改时间');
        }
    }

    /**
     * 保存数据
     *
     * @param integer $id
     * @return void
     */
    private function save($id = 0)
    {
        $data = request()->post();

        $result = $this->validate($data, []);

        if (!$result) {
            $this->error($result);
        }

        if ($id) {
            // 编辑
            $data['update_time'] = date_now();

            if ($data['status'] == 2) {
                $data['review_time'] = date_now();
            }
        } else {
            // 新增
            $data['create_time'] = date_now();
            $data['update_time'] = date_now();
        }

        return $this->doSave($data, $id);
    }

}